"""
路由器集成助手

提供便捷的工具函数，帮助在MarketDataServiceV2中集成路由器。

作者: RedFire Team
创建日期: 2025-10-06
版本: v1.0
"""

import logging
from typing import Optional, List

from app.routing.router import DataSourceRouter
from app.routing.strategies.priority import PriorityRoutingStrategy
from app.routing.strategies.capability_based import CapabilityBasedRoutingStrategy
from app.resilience.circuit_breaker import CircuitBreaker, CircuitBreakerConfig
from app.resilience.rate_limiter import TokenBucketRateLimiter
from app.monitoring.health_monitor import HealthMonitor
from app.orchestration.orchestrator import DataSourceOrchestrator
from app.adapters.manager import AdapterManager
from config.service_config import get_config


logger = logging.getLogger(__name__)


def create_router_from_config(
    adapter_manager: AdapterManager,
    config: Optional[object] = None
) -> DataSourceRouter:
    """
    从配置创建路由器
    
    Args:
        adapter_manager: 适配器管理器
        config: 配置对象（默认使用全局配置）
    
    Returns:
        DataSourceRouter: 配置好的路由器实例
    """
    if config is None:
        config = get_config()
    
    router_config = config.router
    
    # 创建路由器
    router = DataSourceRouter(
        enable_auto_failover=router_config.enable_auto_failover,
        max_failover_attempts=router_config.max_failover_attempts,
        logger=logger
    )
    
    # 注册所有适配器
    for adapter_name in adapter_manager.get_all_adapters():
        adapter = adapter_manager.get_adapter(adapter_name)
        if adapter:
            router.register_adapter(adapter)
            logger.info(f"适配器已注册到路由器: {adapter_name}")
    
    # 添加路由策略
    
    # 1. 优先级策略
    priority_strategy = PriorityRoutingStrategy(
        priority_list=router_config.default_priority,
        enable_fallback=True,
        logger=logger
    )
    router.add_strategy(priority_strategy)
    
    # 2. 能力匹配策略
    capability_strategy = CapabilityBasedRoutingStrategy(
        registry=router.registry,
        min_match_score=router_config.capability_min_score,
        capability_weight=router_config.capability_weight,
        performance_weight=router_config.performance_weight,
        freshness_weight=router_config.freshness_weight,
        reliability_weight=router_config.reliability_weight,
        cost_weight=router_config.cost_weight,
        logger=logger
    )
    router.add_strategy(capability_strategy)
    
    logger.info(f"路由器初始化完成，共添加 2 个策略")
    return router


def create_health_monitor_from_config(
    router: DataSourceRouter,
    config: Optional[object] = None
) -> HealthMonitor:
    """
    从配置创建健康监控器
    
    Args:
        router: 路由器实例
        config: 配置对象
    
    Returns:
        HealthMonitor: 健康监控器实例
    """
    if config is None:
        config = get_config()
    
    monitoring_config = config.monitoring
    resilience_config = config.resilience
    
    if not monitoring_config.enabled:
        logger.warning("健康监控被禁用")
        return None
    
    # 创建健康监控器
    monitor = HealthMonitor(
        check_interval=monitoring_config.check_interval,
        health_check_timeout=resilience_config.health_check_timeout,
        unhealthy_threshold=monitoring_config.unhealthy_threshold,
        logger=logger
    )
    
    # 注册所有适配器
    for adapter_name in router.get_all_adapters():
        adapter = router.get_adapter(adapter_name)
        if adapter:
            monitor.register_adapter(adapter)
    
    logger.info("健康监控器初始化完成")
    return monitor


def create_orchestrator_from_config(
    router: DataSourceRouter,
    config: Optional[object] = None
) -> DataSourceOrchestrator:
    """
    从配置创建编排器
    
    Args:
        router: 路由器实例
        config: 配置对象
    
    Returns:
        DataSourceOrchestrator: 编排器实例
    """
    if config is None:
        config = get_config()
    
    # 创建编排器
    orchestrator = DataSourceOrchestrator(
        router=router,
        logger=logger
    )
    
    logger.info("数据源编排器初始化完成")
    return orchestrator


def setup_resilience_for_adapter(
    adapter_name: str,
    config: Optional[object] = None
) -> dict:
    """
    为适配器设置弹性组件
    
    Args:
        adapter_name: 适配器名称
        config: 配置对象
    
    Returns:
        dict: 包含熔断器和限流器的字典
    """
    if config is None:
        config = get_config()
    
    resilience_config = config.resilience
    
    components = {}
    
    # 创建熔断器
    if resilience_config.circuit_breaker_enabled:
        cb_config = CircuitBreakerConfig(
            failure_threshold=resilience_config.cb_failure_threshold,
            success_threshold=resilience_config.cb_success_threshold,
            timeout=resilience_config.cb_timeout,
            half_open_max_calls=resilience_config.cb_half_open_max_calls
        )
        components['circuit_breaker'] = CircuitBreaker(
            name=adapter_name,
            config=cb_config,
            logger=logger
        )
    
    # 创建限流器
    if resilience_config.rate_limiter_enabled:
        components['rate_limiter'] = TokenBucketRateLimiter(
            name=f"{adapter_name}_limiter",
            rate=resilience_config.rate_limit_requests / resilience_config.rate_limit_window,
            capacity=resilience_config.rate_limit_requests,
            logger=logger
        )
    
    logger.info(f"弹性组件已为适配器 {adapter_name} 设置完成")
    return components


async def initialize_routing_system(
    adapter_manager: AdapterManager,
    config: Optional[object] = None,
    start_monitoring: bool = True
) -> dict:
    """
    初始化完整的路由系统
    
    这是一个便捷函数，一次性创建所有必要的组件。
    
    Args:
        adapter_manager: 适配器管理器
        config: 配置对象
        start_monitoring: 是否启动健康监控
    
    Returns:
        dict: 包含所有组件的字典
    """
    if config is None:
        config = get_config()
    
    logger.info("开始初始化路由系统...")
    
    # 创建路由器
    router = create_router_from_config(adapter_manager, config)
    
    # 创建编排器
    orchestrator = create_orchestrator_from_config(router, config)
    
    # 创建健康监控器
    health_monitor = create_health_monitor_from_config(router, config)
    
    # 启动健康监控
    if health_monitor and start_monitoring:
        await health_monitor.start()
        logger.info("健康监控已启动")
    
    logger.info("路由系统初始化完成 ✓")
    
    return {
        'router': router,
        'orchestrator': orchestrator,
        'health_monitor': health_monitor
    }


async def shutdown_routing_system(components: dict):
    """
    关闭路由系统
    
    Args:
        components: initialize_routing_system 返回的组件字典
    """
    logger.info("开始关闭路由系统...")
    
    # 停止健康监控
    health_monitor = components.get('health_monitor')
    if health_monitor:
        await health_monitor.stop()
        logger.info("健康监控已停止")
    
    logger.info("路由系统已关闭 ✓")

